//
//  ViewController.m
//  testjson
//
//  Created by fcbayern on 2020/11/22.
//  Copyright © 2020 fcbayern. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"
#import "homepage.h"
#import "AFNetworking.h"
#import "SettingsViewController.h"
#import "Masonry.h"
#import "Single.h"
#import "signup.h"
#import "blue.h"
#import "DiscoverSquare.h"
#define RGBACOLOR(R, G, B, A) [UIColor colorWithRed:((R) / 255.0f) green:((G) / 255.0f) blue:((B) / 255.0f) alpha:A]
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
@interface ViewController ()
@property(strong,nonatomic)UITextField * username;
@property(strong,nonatomic)UITextField * password;

@property(strong,nonatomic)UIButton * signup;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBack];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:135/255.0 green:206/255.0 blue:250/255.0 alpha:1];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"登录";
    
    _username = [[UITextField alloc]init];
    _username.placeholder = @"请输入邮箱";
    _username.layer.borderWidth = 1.0f;
    _password = [[UITextField alloc]init];
    _password.placeholder = @"请输入密码";
    _password.layer.borderWidth = 1.0f;
    _password.secureTextEntry = YES;
    _password.layer.cornerRadius = 15;
    _username.layer.cornerRadius = 15;
    [self.view addSubview:_username];
    [self.view addSubview:_password];
    
    [_username mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).offset(self.view.frame.size.height * 0.15);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.7);
        make.height.equalTo(self.view.mas_height).multipliedBy(0.08);
    }];
    
    [_password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(_username.mas_top).offset(self.view.frame.size.height * 0.15);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.7);
        make.height.equalTo(self.view.mas_height).multipliedBy(0.08);
    }];
    
    _signup = [[UIButton alloc]init];
    _signin = [[UIButton alloc]init];
    [_signin setTitle:@"登录" forState:UIControlStateNormal];
    [_signin setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_signup setTitle:@"注册" forState:UIControlStateNormal];
    [_signup setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _signin.backgroundColor = [UIColor colorWithRed:135/255.0 green:206/255.0 blue:250/255.0 alpha:1];
    _signup.backgroundColor =[UIColor colorWithRed:135/255.0 green:206/255.0 blue:250/255.0 alpha:1];
    _signin.layer.cornerRadius = 15;
    _signup.layer.cornerRadius = 15;
    [self.view addSubview:_signin];
    [self.view addSubview:_signup];
    [_signup mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(self.view.frame.size.width * 0.1);
        make.top.equalTo(_password.mas_bottom).offset(self.view.frame.size.height * 0.1);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.3);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.2);
    }];
    [_signin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-self.view.frame.size.width * 0.1);
        make.top.equalTo(_password.mas_bottom).offset(self.view.frame.size.height * 0.1);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.3);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.2);
    }];

    
    [_signin addTarget:self action:@selector(signin:) forControlEvents:UIControlEventTouchUpInside];
    [_signup addTarget:self action:@selector(clicksignup:) forControlEvents:UIControlEventTouchUpInside];
    // Do any additional setup after loading the view.
}

-(void)clicksignup:(id)sender{
    signup * Signup = [[signup alloc]init];
    [self.navigationController pushViewController:Signup animated:YES];
}



-(void)signin:(id)sender{
    NSString * Username = _username.text;
    NSString * Password = _password.text;
    
    
    NSDictionary * parameters = @{
        @"name":Username,
        @"password":Password
    };
    NSString * url2 = @"http://172.18.178.56/api/user/login/pass";
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager POST:url2 parameters:parameters  headers:nil  progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * returnjson = (NSDictionary *)responseObject;
        NSString * checklogin = returnjson[@"State"];
        NSString * errorData = returnjson[@"Data"];
        [Single sharedInstance].check_login = 1;
        
      if([checklogin isEqualToString:@"success"] == 1){
          [Single sharedInstance].wsj_name =Username;
          [Single sharedInstance].wsj_password =Password;
        
            UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"登陆成功" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert1 animated:YES completion:nil];
            AppDelegate *app = [UIApplication sharedApplication].delegate;
            UITabBarController * tabbar = [[UITabBarController alloc ]init];
        
       [[UITabBarItem appearance] setTitleTextAttributes:@{ UITextAttributeTextColor : [UIColor blackColor],UITextAttributeFont:[UIFont fontWithName:@"Marion-Italic" size:14.0]}  forState:UIControlStateNormal];
        
            homepage * view1 = [[homepage alloc]init];
            view1.title = @"我的主页";
            UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:view1];
            [tabbar addChildViewController:nav1];
            UIImage *mypage = [[UIImage imageNamed:@"mypage"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            UIImage *mypage2 = [[UIImage imageNamed:@"mypageact"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            view1.tabBarItem.image = mypage;
            view1.tabBarItem.selectedImage = mypage2;
            DiscoverSquare * testview1 = [[DiscoverSquare alloc]init];
            testview1.title = @"广场";
           UIImage *playground1 = [[UIImage imageNamed:@"playground"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
           UIImage *playground2 = [[UIImage imageNamed:@"playgroundact"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            UINavigationController * nav2 =[[UINavigationController alloc] initWithRootViewController:testview1];
        testview1.tabBarItem.image = playground1;
        testview1.tabBarItem.selectedImage = playground2;
            [tabbar addChildViewController:nav2];
            SettingsViewController * testview2 = [[SettingsViewController alloc]init];
            testview2.title = @"设置中心";
            UINavigationController * nav3 =[[UINavigationController alloc] initWithRootViewController:testview2];
            [tabbar addChildViewController:nav3];
            UIImage *set1 = [[UIImage imageNamed:@"set"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            UIImage *set2 = [[UIImage imageNamed:@"setact"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            testview2.tabBarItem.image = set1;
            testview2.tabBarItem.selectedImage = set2;
            app.window.rootViewController = tabbar;
        
            [app.window makeKeyAndVisible];
       }
        
       else if([checklogin isEqualToString:@"error"] == 1){
            if([errorData isEqualToString:@"not found"] == 1){
                UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"邮箱未注册" preferredStyle:UIAlertControllerStyleAlert];
                           [self presentViewController:alert1 animated:YES completion:nil];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                               [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
                           });
            }
            if([errorData isEqualToString:@"crypto/bcrypt: hashedPassword is not the hash of the given password"] == 1){
                           UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"密码错误" preferredStyle:UIAlertControllerStyleAlert];
                                      [self presentViewController:alert1 animated:YES completion:nil];
                               dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                          [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
                                      });
                       }
            
        }
        else if([checklogin isEqualToString:@"bad_req"] == 1){
            UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"登陆邮箱或密码未输入" preferredStyle:UIAlertControllerStyleAlert];
                   [self presentViewController:alert1 animated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                       [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
                   });
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"false");
    }];
    

}

-(void)setBack{
    CAGradientLayer *l = [[CAGradientLayer alloc] init];
    l.colors = @[(__bridge id)UIColorFromRGB(0x87cefa).CGColor , (__bridge id)UIColorFromRGB(0xffc0cb).CGColor];
    l.startPoint = CGPointMake(0, 0);
    l.endPoint = CGPointMake(1, 1);
    l.frame = self.view.bounds;
    [self.view.layer addSublayer:l];
}
@end
